<?php

class ProductController extends BaseAdminController {

    public $menu = array(
        array('label' => 'Create new product', 'url' => array('product/create')),
        array('label' => 'List of all products', 'url' => array('product/index'))
    );

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('create', 'saveCreate', 'update', 'index', 'delete', 'deleteImage', 'list', 'show', 'content', 'images', 'search'),
                'users' => array(User::model()->getAdmin()->email),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $this->redirect(array('list'));
    }

    /**
     * List all search
     */
    public function actionSearch() {
        $productSearch = new Search;
        if (isset($_POST['Search'])) {
            $productSearch->attributes = $_POST['Search'];
            $keyWord = $productSearch->keyWord;
            $criteria = new CDbCriteria;
            $criteria->distinct = true;
            $criteria->addCondition(array('status =:status'));

//continue with search condition
            if (strlen($keyWord) > 0) {
                $searchCondition = '';
                if ($productSearch->searchByName) {
                    $searchCondition = 'd.name like :keyWord';
                }
                if ($productSearch->searchByContent) {
                    if ($searchCondition == '') {
                        $searchCondition = 'd.content like :keyWord';
                    } else {
                        $searchCondition = ' OR d.content like :keyWord';
                    }
                }
                if (!$productSearch->searchByName && !$productSearch->searchByContent) {
                    $searchCondition = 'd.name like :keyWord OR d.content like :keyWord';
                }
                if ($searchCondition != '') {
                    $searchCondition = ' AND (' . $searchCondition . ')';
                }
            }
            $criteria->join = 'INNER JOIN product_detail d ON t.id=d.product_id ' . $searchCondition;
            $categoryParent = Category::model()->getCategoryParent('Product');
            $criteria->params = array(':status' => 'yes', ':keyWord' => '%' . $keyWord . '%'); //
            $dataProvider = new CActiveDataProvider('Product', array(
                'criteria' => $criteria,
                'pagination' => array(
                    'pageSize' => Constant::PAGE_SIZE,
                ),
            ));
            $productSearch = new Search;
            $this->render('list', array(
                'productSearch' => $productSearch,
                'dataProvider' => $dataProvider,
            ));
        }
    }

    /**
     * Manages all models.
     */
    public function actionList() {
        $productSearch = new Search;
        $criteria = new CDbCriteria;
        $criteria->with = array(
            'category',
        );
        $criteria->condition = "status =:status";
        $criteria->params = array(':status' => 'yes');
        $dataProvider = new CActiveDataProvider('Product', array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => Constant::PAGE_SIZE,
            ),
        ));
        $this->render('list', array(
            'productSearch' => $productSearch,
            'dataProvider' => $dataProvider,
        ));
    }

    public function renameImage($imageName) {
        $newName = str_replace(array(' ', '\\', '/', ',', '(', ')', '-', '"', '\'', '%'), '_', $imageName);
        $newName = time() . '_' . $newName;
        return $newName;
    }

    public function createStateList() {
        $stateArray = array();
        $state = array();
        $state['id'] = 1;
        $state['name'] = 'In stock';
        $stateArray[] = $state;
        $state['id'] = 2;
        $state['name'] = 'Out of stock';
        $stateArray[] = $state;
        return $stateArray;
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $categories = Category::model()->getCategories('en');
        $producers = Producer::model()->findAll();
        $states = $this->createStateList();
        $product = new Product;
        $productDetails = array();
        for ($i = 0; $i < 1; $i++) {
            $productDetail = new ProductDetail;
            if ($i == 0) {
                $productDetail->language = 'en';
            } else {
                $productDetail->language = 'vi';
            }
            $productDetails[] = $productDetail;
        }

        $productImage = new ProductImage;
        $message = ''; //store message;
// Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($product);

        if (isset($_POST['Product']) && isset($_POST['ProductDetail'])) {
            $product->attributes = $_POST['Product'];
            $valid = true;
            foreach ($productDetails as $i => $productDetail) {
                $productDetail->attributes = $_POST['ProductDetail'][$i];
                $productDetails[$i] = $productDetail;
                $valid = $productDetail->validate() && $valid;
            }
            if ($valid) {
//get images and check
                $images = CUploadedFile::getInstancesByName('path');
                if (isset($images) && count($images) > 0) {
                    $canSave = true;
                    foreach ($images as $image => $pic) {
                        $imageName = $this->renameImage($pic->name);
                        /* if (ProductImage::model()->existedImagePath('contents/uploads/images/product/' . $imageName)) {//check duplicated images path in database
                          $message = '"' . $imageName . '":' . Yii::t('product', 'existedImageName');
                          $canSave = false;
                          break;
                          } else { */
                        if (strlen('contents/uploads/images/product/' . $imageName) > 255) {//check length of images name
                            $message = '"' . $imageName . '":' . Yii::t('product', 'longImageName');
                            $canSave = false;
                            break;
                        }
                    }
                    if ($canSave) {
//begin upload images
                        $imagesName = array();
                        foreach ($images as $image => $pic) {
                            $imageName = $this->renameImage($pic->name);
                            $path = Yii::getPathOfAlias('webroot.contents.uploads.images.product') . DIRECTORY_SEPARATOR . $imageName;
                            if ($pic->saveAs($path)) {
                                $imagesName[] = $imageName;
                            }
                        }

//save model to database
                        try {
                            if ($product->save()) {
                                foreach ($productDetails as $productDetail) {
                                    $productDetail->product_id = $product->id;
                                    $productDetail->save();
                                }

//create list product images                               
                                foreach ($imagesName as $imageName) {
                                    $productImage = new ProductImage;
                                    $productImage->product_id = $product->id;
                                    $productImage->path = 'contents/uploads/images/product/' . $imageName;
                                    $saved = $productImage->save();
                                    $r = $productImage->getErrors();
                                    if (!$saved) {//if saving fail, delete uploaded images
                                        $path = Yii::getPathOfAlias('webroot.contents.uploads.images.product') . DIRECTORY_SEPARATOR . $imageName;
                                        unlink($path);
                                    }
                                }
                                Yii::app()->user->setFlash('message', Yii::t('product', 'successCreate'));
                                $this->refresh();
                                $this->redirect(array('create'));
                            }
                        } catch (Exception $ex) {
                            echo $ex->getMessage();
                            Yii::app()->user->setFlash('message', Yii::t('product', 'failCreate'));
                            $this->redirect(array('create'));
                        }
                    }
                } else {
                    $message = Yii::t('product', 'notUploadImage');
                }
            } else {
                $message = Yii::t('product', 'notValid');
            }
            $message = Yii::t('product', 'failCreate');
        }

        $this->render('create', array(
            'message' => $message,
            'product' => $product,
            'categories' => $categories,
            'producers' => $producers,
            'states' => $states,
            'productDetails' => $productDetails,
            'productImage' => $productImage,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $categories = Category::model()->getCategories('en');
        $producers = Producer::model()->findAll();
        $states = $this->createStateList();
        $product = $this->loadModel($id);
        $productDetails = $product->productDetails;
        $productImage = new ProductImage;
        $message = ''; //store message;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($product);

        if (isset($_POST['Product']) && isset($_POST['ProductDetail'])) {
            $product->attributes = $_POST['Product'];
            $valid = true;
            foreach ($productDetails as $i => $productDetail) {
                $productDetail->attributes = $_POST['ProductDetail'][$i];
                $productDetails[$i] = $productDetail;
                $valid = $productDetail->validate() && $valid;
            }
            if ($valid) {
//get images and check
                $canSave = true;
                $images = CUploadedFile::getInstancesByName('path');
                if (isset($images) && count($images) > 0) {
                    foreach ($images as $image => $pic) {
                        $imageName = $this->renameImage($pic->name);
                        /* if (ProductImage::model()->existedImagePath('contents/uploads/images/product/' . $imageName)) {//check duplicated images path in database
                          $message = '"' . $imageName . '":' . Yii::t('product', 'existedImageName');
                          $canSave = false;
                          break;
                          } */
                        if (strlen('contents/uploads/images/product/' . $imageName) > 255) {//check length of images name
                            $message = '"' . $imageName . '":' . Yii::t('product', 'longImageName');
                            $canSave = false;
                            break;
                        }
                    }
                }
//save to database
                if ($canSave) {
//begin upload images
                    $imagesName = array();
                    foreach ($images as $image => $pic) {
                        $imageName = $this->renameImage($pic->name);
                        $path = Yii::getPathOfAlias('webroot.contents.uploads.images.product') . DIRECTORY_SEPARATOR . $imageName;
                        if ($pic->saveAs($path)) {
                            $imagesName[] = $imageName;
                        }
                    }
//save model
                    try {
                        if ($product->save()) {
                            foreach ($productDetails as $productDetail) {
                                $productDetail->save();
                            }
//create product images and save
                            foreach ($imagesName as $imageName) {
                                $productImage = new ProductImage;
                                $productImage->product_id = $product->id;
                                $productImage->path = 'contents/uploads/images/product/' . $imageName;
                                $saved = $productImage->save();
                                if (!$saved) {//if saving fail, delete uploaded images
                                    $path = Yii::getPathOfAlias('webroot.contents.uploads.images.product') . DIRECTORY_SEPARATOR . $imageName;
                                    unlink($path);
                                }
                            }
                            Yii::app()->user->setFlash('message', Yii::t('product', 'successUpdate'));
                            $this->redirect(array('list'));
                        }
                    } catch (Exception $ex) {
                        echo $ex->getMessage();
                        Yii::app()->user->setFlash('message', Yii::t('product', 'failUpdate'));
                        $this->redirect(array('list'));
                    }
                }
            } else {
                $message = Yii::t('product', 'notValid');
            }
            $message = Yii::t('product', 'failUpdate');
        }


        $this->render('update', array(
            'message' => $message,
            'categories' => $categories,
            'producers' => $producers,
            'states' => $states,
            'product' => $product,
            'productDetails' => $productDetails,
            'productImage' => $productImage,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
            $product = $this->loadModel($id);
            $product->status = 'no';
            $product->update();

// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, Yii::t('default', 'notValidWeb'));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $criteria = new CDbCriteria;
        $criteria->condition = 'status=:status';
        $criteria->params = array(':status' => 'yes');
        $product = Product::model()->findByPk($id, $criteria);
        if ($product === null)
            throw new CHttpException(404, Yii::t('default', 'notExistWeb'));
        return $product;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($product) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-form') {
            echo CActiveForm::validate($product);
            Yii::app()->end();
        }
    }

    /**
     * show image by path
     */
    public function actionShow($path) {
        $imagePath = $path;
        Yii::app()->clientScript->scriptMap['jquery.js'] = false;
        $this->renderPartial('viewImage', array('imagePath' => $imagePath,), false, true);
    }

    /**
     * action Content
     */
    public function actionContent($id) {//Yii::app()->createUrl(\'product/content\',array(\'id\'=>$data->id)
        $product = Product::model()->findByPk($id);
        $productDetails = $product->productDetails;
//  Yii::app()->clientScript->scriptMap['jquery.js'] = false;
        $this->renderPartial('showContent', array('productDetails' => $productDetails,), false, true);
    }

    /**
     * action Images
     */
    public function actionImages($id) {
        $product = Product::model()->findByPk($id);
        $productImages = $product->productImages;
        Yii::app()->clientScript->scriptMap['jquery.js'] = false;
        $this->renderPartial('showImages', array('productImages' => $productImages,), false, true);
    }

    /**
     * delete image update
     */
    public function actionDeleteImage($id) {
        $productImage = ProductImage::model()->findByPk($id);
        $productImage->delete();
// die;
    }

}
